<template>
  <!-- 页面整体容器：包含查询区域、列表区域以及弹窗 -->
  <div class="department-management-page">
    <!-- 查询条件卡片 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryForm" label-width="80px" class="filter-form" inline>
        <el-form-item label="部门名称">
          <el-input
            v-model="queryForm.keyword"
            placeholder="支持模糊搜索部门名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表卡片：树形属性列表 -->
    <el-card class="list-card" shadow="never">
      <div class="table-toolbar">
        <div class="table-title">部门列表</div>
        <div class="toolbar-actions">
          <el-button type="primary" @click="openCreateDialog">新增部门</el-button>
        </div>
      </div>

      <div class="table-wrapper" v-loading="loading">
        <el-empty v-if="!loading && !tableData.length" description="暂无部门数据" />
        <el-table
          v-else
          :data="tableData"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :default-expand-all="false"
          border
          stripe
          style="width: 100%"
          :indent="20"
        >
          <el-table-column prop="name" label="部门名称" min-width="250" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="department-name">{{ row.name }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="code" label="部门编码" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.code || '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="parentName" label="上级部门" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.parentName || '顶级部门' }}
            </template>
          </el-table-column>

          <el-table-column prop="manager" label="负责人" min-width="100" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.manager || '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="phone" label="联系电话" min-width="130" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.phone || '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="sort" label="排序" width="80" align="center">
            <template #default="{ row }">
              {{ row.sort ?? 0 }}
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" min-width="160" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.createTime || '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.description || '暂无描述' }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="openEditDialog(row)">
                编辑
              </el-button>
              <el-button type="danger" link size="small" @click="confirmDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="pagination.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 / 编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" destroy-on-close>
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="父级部门" prop="parentId">
          <el-tree-select
            v-model="formModel.parentId"
            :data="departmentTreeOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择父级部门（不选则为顶级）"
            clearable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formModel.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formModel.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="formModel.manager" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formModel.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formModel.sort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formModel.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formModel.description"
            type="textarea"
            :rows="3"
            placeholder="请输入部门描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/Http/http'

interface DepartmentRecord {
  id: number | string | null
  parentId: number | string | null
  name: string
  code: string
  manager?: string
  phone?: string
  sort: number
  status: number
  description?: string
  createTime?: string
  parentName?: string
  children?: DepartmentRecord[]
  hasChildren?: boolean
}

// ===================== 页面状态 =====================
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const tableData = ref<DepartmentRecord[]>([])
const departmentTreeOptions = ref<DepartmentRecord[]>([])

// ===================== 查询表单 + 分页 =====================
const queryForm = reactive({
  keyword: '',
})

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

type DepartmentForm = DepartmentRecord
const defaultFormState = (): DepartmentForm => ({
  id: null,
  parentId: null,
  name: '',
  code: '',
  manager: '',
  phone: '',
  sort: 0,
  status: 1,
  description: '',
})

const formModel = reactive<DepartmentForm>(defaultFormState())
const formRef = ref<FormInstance>()

const formRules = reactive<FormRules<DepartmentForm>>({
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
})

const dialogTitle = computed(() => (dialogMode.value === 'create' ? '新增部门' : '编辑部门'))

// ===================== 数据格式化工具 =====================
const normalizeListResponse = (payload: any) => {
  if (!payload) {
    return { items: [], total: 0 }
  }

  if (Array.isArray(payload)) {
    return { items: payload, total: payload.length }
  }

  if (Array.isArray(payload.listResult)) {
    return {
      items: payload.listResult,
      total: payload.totalcount ?? payload.listResult.length,
    }
  }

  if (Array.isArray(payload.items)) {
    return { items: payload.items, total: payload.total ?? payload.items.length }
  }

  if (Array.isArray(payload.result)) {
    return { items: payload.result, total: payload.totalcount ?? payload.result.length }
  }

  if (payload.data) {
    return normalizeListResponse(payload.data)
  }

  return { items: [], total: 0 }
}

// ===================== 部门树数据 =====================
const fetchDepartmentTree = async () => {
  try {
    const { data } = await myaxios.get('/api/Department/GetDepartmentTree')
    const normalized = data?.result ?? data?.data ?? data
    departmentTreeOptions.value = Array.isArray(normalized) ? normalized : normalized?.items ?? []
  } catch (error) {
    console.error('获取部门树失败', error)
    departmentTreeOptions.value = []
  }
}

// ===================== 列表数据 =====================
const enhanceDepartmentTree = (
  list: DepartmentRecord[] = [],
  parent?: DepartmentRecord | null
): DepartmentRecord[] => {
  return list.map((item) => {
    const enhanced: DepartmentRecord = {
      ...item,
      parentName: parent?.name ?? '顶级部门',
      hasChildren: !!(item.children && item.children.length > 0),
    }
    if (item.children && item.children.length) {
      enhanced.children = enhanceDepartmentTree(item.children, item)
    }
    return enhanced
  })
}

const fetchDepartmentList = async () => {
  loading.value = true
  try {
    const { data } = await myaxios.get('api/Users/GetDepartments', {
      params: {
        PageIndex: pagination.pageIndex,
        PageSize: pagination.pageSize,
        keyword: queryForm.keyword,
      },
    })

    const normalized = normalizeListResponse(data?.result ?? data)
    const items = Array.isArray(normalized.items) ? (normalized.items as DepartmentRecord[]) : []
    tableData.value = enhanceDepartmentTree(items)
    pagination.total = normalized.total ?? items.length ?? 0
  } catch (error) {
    console.error('获取部门列表失败', error)
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageIndex = 1
  fetchDepartmentList()
}

const handleReset = () => {
  queryForm.keyword = ''
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchDepartmentList()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchDepartmentList()
}

// ===================== 弹窗交互 =====================
const resetFormModel = () => {
  Object.assign(formModel, defaultFormState())
  formRef.value?.clearValidate()
}

const openCreateDialog = () => {
  dialogMode.value = 'create'
  resetFormModel()
  dialogVisible.value = true
}

const openEditDialog = (row: DepartmentRecord) => {
  dialogMode.value = 'edit'
  resetFormModel()
  Object.assign(formModel, row)
  dialogVisible.value = true
}

// ===================== 新增 / 编辑 / 删除 =====================
const submitForm = () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    const request =
      dialogMode.value === 'create'
        ? myaxios.post('/api/Department/CreateDepartment', formModel)
        : myaxios.put('/api/Department/UpdateDepartment', formModel)

    request
      .then((res) => {
        if (res.data?.code === 200 || res.status === 200) {
          ElMessage.success(dialogMode.value === 'create' ? '新增成功' : '更新成功')
          dialogVisible.value = false
          fetchDepartmentList()
          fetchDepartmentTree()
        } else {
          ElMessage.error(res.data?.message ?? '操作失败')
        }
      })
      .catch((error) => {
        console.error('保存部门失败', error)
        ElMessage.error('保存失败，请稍后再试')
      })
      .finally(() => {
        submitLoading.value = false
      })
  })
}

const confirmDelete = (row: DepartmentRecord) => {
  if (!row?.id) return
  ElMessageBox.confirm(`确定要删除部门「${row.name}」吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
  })
    .then(async () => {
      try {
        await myaxios.delete('/api/Department/DeleteDepartment', { data: { id: row.id } })
        ElMessage.success('删除成功')
        if (tableData.value.length === 1 && pagination.pageIndex > 1) {
          pagination.pageIndex -= 1
        }
        fetchDepartmentList()
        fetchDepartmentTree()
      } catch (error) {
        console.error('删除部门失败', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

// ===================== 生命周期 =====================
onMounted(() => {
  fetchDepartmentTree()
  fetchDepartmentList()
})
</script>

<style scoped>
.department-management-page {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-card {
  border-radius: 8px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 24px;
}

.list-card {
  border-radius: 8px;
}

.list-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
}

.toolbar-actions {
  display: flex;
  gap: 12px;
}

.table-wrapper {
  flex: 1;
  min-height: 360px;
}

.department-name {
  font-weight: 500;
  color: #303133;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table__row) {
  cursor: default;
}

:deep(.el-table .cell) {
  padding: 8px 12px;
}

/* 树形表格样式增强 */
:deep(.el-table__expand-icon) {
  font-size: 14px;
  color: #606266;
  transition: transform 0.2s;
}

:deep(.el-table__expand-icon:hover) {
  color: #409eff;
}

:deep(.el-table__placeholder) {
  display: inline-block;
  width: 20px;
}

/* 树形层级视觉增强 */
:deep(.el-table__body tr.el-table__row--level-1) {
  background-color: #fafafa;
}

:deep(.el-table__body tr.el-table__row--level-2) {
  background-color: #f5f7fa;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
